package aiku.numericalcontroloa.Service.Impl;

import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.*;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderGoodsMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderMapper;
import aiku.numericalcontroloa.Model.Dto.AfterSalesDto;
import aiku.numericalcontroloa.Model.Entity.Clients;
import aiku.numericalcontroloa.Model.Entity.Devices;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.Order;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderGoods;
import aiku.numericalcontroloa.Model.Entity.User;
import aiku.numericalcontroloa.Model.Vo.AfterSalesPageVo;
import aiku.numericalcontroloa.Model.Vo.AfterSalesVo;
import aiku.numericalcontroloa.Model.Vo.OrderManagement.OrderGoodsVo;
import aiku.numericalcontroloa.Service.AfterRecordsService;
import aiku.numericalcontroloa.enums.RoleEnum;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import aiku.numericalcontroloa.Model.Entity.AfterSales;
import aiku.numericalcontroloa.Service.AfterSalesService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
* @author 马
* @description 针对表【after_sales】的数据库操作Service实现
* @createDate 2024-03-14 15:27:10
*/
@Service
public class AfterSalesServiceImpl extends ServiceImpl<AfterSalesMapper, AfterSales>
    implements AfterSalesService{
    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Autowired
    private AfterRecordsMapper afterRecordsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ClientsMapper clientsMapper;
    @Autowired
    private DevicesMapper devicesMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    /**
     * 售后获取派单记录,分页查询
     * @return
     */
    @Override
    public Result afterDispatch(Integer page, Integer size) {
        // TODO 权限还未做
        Page<AfterSales> pages = new Page<>(page, size);

        //获取当前用户
        User user = userMapper.selectById(StpUtil.getLoginId().toString());
        LambdaQueryWrapper<AfterSales> afterSalesLQW = new LambdaQueryWrapper<>();
        // 管理员查所有
        if (!user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString())){
            // 售后查询个人记录
            afterSalesLQW.eq(AfterSales::getUserId, user.getId());
        }
        List<AfterSales> afterSalesList = afterSalesMapper.selectPage(pages,afterSalesLQW).getRecords();

        if (afterSalesList.size()<=0){
            return Result.error(201,"暂无售后记录");
        }
        //这件事售后派单信息
        //TODO 拿到订单id去查询订单信息,然后合并Vo
        //返回VO
        AfterSalesPageVo afterSalesPageVo = new AfterSalesPageVo();
        List<AfterSalesVo> afterSalesVoList = new ArrayList<>();
        for (AfterSales afterSales : afterSalesList) {
            AfterSalesVo afterSalesVo = new AfterSalesVo();
            BeanUtils.copyProperties(afterSales, afterSalesVo);
            // 查询订单信息，设置订单流水号
            Order order = orderMapper.selectById(afterSales.getOrderId());
            afterSalesVo.setSn(order.getSn());
            // 查询并设置客户信息
            Clients clients = clientsMapper.selectByIdWithDelete(order.getClientsId());
            afterSalesVo.setUserName(clients.getName());
            afterSalesVo.setPhone(clients.getPhone());
            // 查询并设置产品信息
            Devices devices = devicesMapper.selectById(order.getGoodsId());
            afterSalesVo.setPartName(devices.getPartName());
            afterSalesVo.setKsModel(devices.getModel());
            afterSalesVoList.add(afterSalesVo);
        }
        afterSalesPageVo.setAfterSalesVoList(afterSalesVoList);
        afterSalesPageVo.setTotal(Long.valueOf(afterSalesVoList.size()));
        return Result.success(afterSalesPageVo);
    }

    @Override
    public Result afterSales(AfterSales afterSales) {
        //查询有无该售后记录
        AfterSales aft = afterSalesMapper.selectById(afterSales.getAfterSalesId());
        if (aft == null){
            return new Result(HttpStatus.BAD_REQUEST,"无该售后记录");
        }
        AfterSales sales = new AfterSales();
        sales.setAfterSalesId(afterSales.getAfterSalesId());
        sales.setInstallationTime(afterSales.getInstallationTime());
        sales.setTraining(afterSales.getTraining());
        afterSalesMapper.updateById(sales);
        return Result.success("保存成功");
    }

    @Override
    public Result getAfterSaleList(AfterSalesDto afterSalesDto) {
        if (afterSalesDto == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数(afterSalesDto为空)");
        }
        if (afterSalesDto.getCurrentPage() == null || afterSalesDto.getPageSize() == null){
            return new Result(HttpStatus.BAD_REQUEST,"缺少参数(分页参数为空)");
        }
        Page<AfterSales> afterSalesPage = new Page<>(afterSalesDto.getCurrentPage(),afterSalesDto.getPageSize());

        User loginUser = userMapper.selectById(StpUtil.getLoginIdAsString());
        boolean root = loginUser.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString()) ||
                loginUser.getRoleId().equals(RoleEnum.ROLE_5.getCodeToString());

        LambdaQueryWrapper<AfterSales> afterSalesLQW = new LambdaQueryWrapper<>();
        afterSalesLQW.orderByDesc(AfterSales::getAfterSalesTime);
        // 条件查询
        if (root && (afterSalesDto.getUserId() != null && !afterSalesDto.getUserId().isEmpty())){
            // 根据售后人员查询
            afterSalesLQW.eq(AfterSales::getUserId,afterSalesDto.getUserId());
        }else if (!root){
            afterSalesLQW.eq(AfterSales::getUserId,loginUser.getId());
        }
        List<AfterSales> afterSalesList = afterSalesMapper.selectPage(afterSalesPage, afterSalesLQW).getRecords();
        List<AfterSalesVo> afterSalesVoList = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        if (afterSalesList.isEmpty()){
            map.put("total",afterSalesPage.getTotal());
            map.put("afterSalesVoList",afterSalesVoList);
            return Result.success("查询成功",map);
        }
        
        // 查售后人员
        Set<String> userIdList = afterSalesList.stream().map(AfterSales::getUserId).collect(Collectors.toSet());
        List<User> userList = userMapper.selectBatchByIdWithDelete(userIdList);
        // 处理成map，根据userId获取用户
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        // 查询订单
        List<String> orderIdList = afterSalesList.stream().map(AfterSales::getOrderId).collect(Collectors.toList());
        List<Order> orderList = orderMapper.selectBatchIdWithDelete(orderIdList, null);
        Map<String, Order> orderMap = orderList.stream().collect(Collectors.toMap(Order::getId, Function.identity()));
        // 查客户
        Set<String> clientsIdList = orderList.stream().map(Order::getClientsId).collect(Collectors.toSet());
        List<Clients> clientsList = clientsMapper.selectBatchByIdWithDelete(clientsIdList);
        // 根据订单id获取客户
        Map<String, Clients> clientsMap = orderList.stream().collect(Collectors.toMap(Order::getId, order -> clientsList.stream()
                .filter(clients -> clients.getId().equals(order.getClientsId()))
                .findFirst()
                .orElse(null)));
        // 查询订单产品
        LambdaQueryWrapper<OrderGoods> orderGoodsLQW = new LambdaQueryWrapper<>();
        orderGoodsLQW.in(OrderGoods::getOrderId,orderIdList);
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(orderGoodsLQW);
        Set<String> devicesIdList = orderGoodsList.stream().map(OrderGoods::getGoodsId).collect(Collectors.toSet());
        // 查产品
        List<Devices> devicesList = devicesMapper.selectBatchByIdWithDelete(devicesIdList);
        // 处理成map，根据产品id获取产品
        Map<String, Devices> devicesMap = devicesList.stream().collect(Collectors.toMap(Devices::getId, Function.identity()));
        // 处理成map,根据订单id获取产品列表
        Map<String,List<OrderGoodsVo>> orderGoodsMap = new HashMap<>();
        for (OrderGoods orderGoods : orderGoodsList){
            Devices devices = devicesMap.get(orderGoods.getGoodsId());
            OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
            BeanUtils.copyProperties(orderGoods,orderGoodsVo);
            orderGoodsVo.setPartName(devices.getPartName());
            orderGoodsVo.setModel(devices.getModel());
            orderGoodsVo.setCount(devices.getCount());
            orderGoodsVo.setImage(devices.getImage());
            orderGoodsVo.setPrice(devices.getPrice());
            orderGoodsVo.setDevicesDescribe(devices.getDevicesDescribe());
            orderGoodsVo.setRemark(devices.getRemark());
            if (orderGoodsMap.containsKey(orderGoodsVo.getOrderId())){
                orderGoodsMap.get(orderGoodsVo.getOrderId()).add(orderGoodsVo);
            }else {
                List<OrderGoodsVo> orderGoodsVoList = new ArrayList<>();
                orderGoodsVoList.add(orderGoodsVo);
                orderGoodsMap.put(orderGoodsVo.getOrderId(),orderGoodsVoList);
            }
        }
        for (AfterSales afterSales : afterSalesList){
            Clients clients = clientsMap.get(afterSales.getOrderId());
            Order order = orderMap.get(afterSales.getOrderId());
            User user = userMap.get(afterSales.getUserId());
            List<OrderGoodsVo> orderGoodsVoList = orderGoodsMap.get(afterSales.getOrderId());
            AfterSalesVo afterSalesVo = new AfterSalesVo();
            BeanUtils.copyProperties(afterSales,afterSalesVo);
            afterSalesVo.setSn(order.getSn());
            afterSalesVo.setClientsName(clients.getName());
            afterSalesVo.setPhone(clients.getPhone());
            afterSalesVo.setUserName(user.getNickName());
            afterSalesVo.setGoodsList(orderGoodsVoList);
            afterSalesVoList.add(afterSalesVo);
        }
        map.put("total",afterSalesPage.getTotal());
        map.put("afterSalesVoList",afterSalesVoList);
        return Result.success("查询成功",map);
    }
}




